<template>
	<view>
		<view class="top">
			{{details.title}}
		</view>
		<view class="line"/>
		<view class="content">
			<view style="display: flex;padding: 20upx 0 40upx 0">
				<image @click="goUrl"   class="content-image"
					   :src="details.head">
				</image>
				<view>
					<view class="content-name">{{details.userName}}</view>
					<view class="content-time">{{details.createTime}}</view>
				</view>
			</view>
			<view class="audio-wrap" v-if="item.type.value=='audio'" v-for="(item,index) in details.attachments">
				<text class="iconfont" @click="audioPlay(item,index)" style="margin:60upx 20upx 0 20upx;font-size:60upx;color: rgba(155, 155, 155, 1);">
					{{item.flag?'&#xe62c;':'&#xe64e;'}}</text>
				<view style="margin: 20upx;width: 100%">
					<view class="audio-title">
						{{item.name}}
					</view>
					<slider :value="item.currentTime" style="margin: 0 !important;" activeColor="black" block-size="12"
							:max="item.duration"
							@changing="(e)=>{sliderChanging(e,item)}"	@change="(e)=>{sliderChange(e,item)}" step="10" />
					<view class="audio-time">
						<span>{{item.currentTimeText}}</span>
						<span>{{item.durationText}}</span>
					</view>
				</view>
			</view>
<!--			<audio poster="{{poster}}"  name="{{name}}" author="{{author}}" src="{{src}}" id="myAudio" controls loop></audio>-->
			<view class="content-text" v-html="details.content">
			</view>
		</view>
		<view class="footer">
			<view class="share">
				<text class="iconfont" style="font-size:44upx;color: #7f7f7f;">
					&#xe66f;</text>
				<view class="share-text">收藏</view>
			</view>
			<view style="display: flex">
				<button style="background: white;color:rgba(183, 183, 183, 1);font-size: 26upx;font-family: PingFangSC-regular;height:100upx;width: 150upx;text-align: center"
						open-type="share">
					<text class="iconfont"
						  style="position:relative;top:-32upx;font-size:44upx;color: #2d8fff">&#xe659;</text>
					<view class="share-text" style="position:relative;top:-78upx;">分享</view>
				</button>
<!--				<view class="share">-->
<!--					<text  class="iconfont" style="font-size:44upx;color: #2d8fff;">-->
<!--						&#xe659;</text>-->
<!--					<view  class="share-text">分享</view>-->
<!--				</view>-->
				<view class="share" style="margin-left: 30upx" @click="can">
					<view style="margin-top: -8upx;margin-bottom: 8upx">
						<text  class="iconfont" style="font-size:44upx;color: #2d8fff;">
							&#xe619;</text>
					</view>
					<view class="share-text">生成海报</view>
				</view>
			</view>
		</view>
		<uni-popup :show="popup"  mode="fixed" position="bottom" type="bottom"
				   msg="">
			<view>
				<view style="text-align: right;margin-right: 30upx">
					<text @click="popup=false" class="iconfont" style="font-size:44upx;color: #868686;">
						&#xe606;</text>
				</view>
				<view  class="popup" :style="{height:height+'px'}">
					<image style="width: 100%;height: 100%" v-if="canvasToTempFilePath" :src="canvasToTempFilePath"></image>
					<canvas v-else canvas-id='canvas_poster' style="width: 100%;height: 100%"></canvas>
				</view>
				<view class="save" @click="saveimg">
					<text class="iconfont" style="font-size:44upx;color: white;">
						&#xe619;</text>
					保存</view>
			</view>
			<!--			<view class="popup">-->
<!--				<image src="../../static/img/share.png" style="width: 100%;height: 30.73vw"/>-->
<!--				<view style="display: flex;padding: 30upx">-->
<!--					<image @click="goUrl"   class="content-image"-->
<!--						   src="http://n.sinaimg.cn/news/transform/700/w1000h500/20190722/e14c-iaantfi6168637.jpg">-->
<!--					</image>-->
<!--					<view>-->
<!--						<view style="line-height: 28upx" class="content-name">姓名</view>-->
<!--						<view style="line-height: 28upx" class="content-time">刚刚</view>-->
<!--					</view>-->
<!--				</view>-->
<!--				<view style="line-height: 36upx;text-align: left;padding: 0 30upx" class="content-text">-->
<!--					微商是自己进货自己卖，有公司有产品，类似全国连锁，有团队，代理，省去了租店面的钱，可以自己开微店或淘宝店，很简单，这就是微商。-->
<!--					其实微商呢只是利用碎片时间来做，不用你一整天都抱着个手机的，像我们很多代理都是宝妈都有工作都要带小孩呀！有的上班兼职做，他们都利用空闲时间做，都做的非常好。-->
<!--				</view>-->
<!--				<view style="display: flex;justify-content:space-between;margin-top: 20upx;padding: 0 30upx">-->
<!--					<view>-->
<!--						<view style="width: 50upx;height: 10upx;background: #F5D42D"/><br>-->
<!--						<view  class="content-text" style="margin-top: 20upx;text-align: left">长按识别小程序，查看更多</view>-->
<!--					</view>-->
<!--					<image @click="goUrl" style="width: 180upx;height: 180upx"-->
<!--						   src="http://n.sinaimg.cn/news/transform/700/w1000h500/20190722/e14c-iaantfi6168637.jpg">-->
<!--					</image>-->
<!--				</view>-->
<!--			</view>-->
		</uni-popup>
		<view class='open-seting-bg'v-if='openSet' catchtap='cancleSet'>
			<view class='open-set-inner'>
				<view class='set-title'>是否打开授权设置？</view>
				<view class='btn-openset'>
					<view catchtap='cancleSet'>取消</view>
					<view>
						<button open-type='openSetting' class='button-style' catchtap='cancleSet'>确定</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import API from '../../common/api.js';
	import Util from '../../common/util.js';
	import uniPopup from "@/components/uni-popup/uni-popup.vue"
	export default {
		components:{
			uniPopup
		},
		data() {
			return {
				width: uni.getSystemInfoSync().windowWidth,
				height:0,
				id:0,
				img:'',
				img2:'',
				team:uni.getStorageSync('team')?JSON.parse(uni.getStorageSync('team')):{name:'团队',id:0},
				details:{},
				index:-1,
				openSet:false,
				key:'',
				list:[],
				innerAudioContext:null,
				flag:false,
				timer:null,
				duration:0,
				currentTime:0,
				currentTimeText:'00:00',
				timeTemp:0,
				timeFlag:false,
				durationText:'00:00',
				popup:false,
				canvasToTempFilePath:'',
				showShareImg:false,
				conWidth:0,
				cc:'似131231是的13131231是的13131231是的13131231是的13131231你的世界妇女是的13131231你的世界妇女是的13131231你的世界妇女的几个悲伤的价格比a是的13131231你的世界妇' +
						'的吧,是的方式能能能能能数能数数数'
			}
		},
		onLoad(options){
			console.log(options.id,45555)
			this.id=options.id||1068
			uni.setNavigationBarTitle({
				title:this.team.name
			})
			this.getData()
			this.audio()

			let url=this.team.shareImage
			uni.getImageInfo({
				src: url,//服务器返回的图片地址
				success: res=>{
					//res.path是网络图片的本地地址
					this.img=res.path
					console.log(res.path)
					// this.can(res.path)
					this.getData(true)

				},
				fail: function (res) {
					//失败回调
				}
			});
		},

		methods:{
			getData(){
				API.knowledgeDetail({targetId:this.id}).then(res=>{
					if(res.status==200){
						res.data.createTime=Util.formatTime(res.data.createTime)
						res.data.attachments.map(r=>{
							r.currentTimeText='00:00'
							r.currentTime=0
							r.durationText=this.getText(r.length)
							r.duration=r.length
							r.flag=false
							r.timeFlag=false
						})
						this.details=res.data
						this.details.shareContent=res.shareContent
						if(res.user){
							this.details.userName=res.user.extra.wxName
							this.details.head=res.user.extra.wxAvatar
						}else{
							this.details.userName=this.team.name
							this.details.head=this.team.coverImage
						}
						let url2=this.details.head
						uni.getImageInfo({
							src: url2,//服务器返回的图片地址
							success: r=>{
								//res.path是网络图片的本地地址
								this.img2=r.path
								console.log(this.img,4145454545)
							},
							fail: function (r) {
								//失败回调
							}
						});
					}else{
						uni.showModal({
							title: '提示',
							content: '加载失败',
							showCancel: false,
						});
					}
				})
			},
			save(){
				console.log(11)
				uni.canvasToTempFilePath({
					canvasId: 'canvas_poster',
					success: res=>{
						console.log(res.tempFilePath,666)
						this.canvasToTempFilePath = res.tempFilePath // 返回的图片地址保存到一个变量里
						uni.showToast({
							title: '生成海报成功',
							icon: 'success'
						})
						// this.saveimg()
					},
					fail: (error)=>{
						console.log(error)
						uni.showToast({
							title: '生成海报失败',
							icon: 'none'
						})
					},
					complete:()=>{
						// uni.hideLoading()
						// uni.hideToast()
					}
				})
			},
			saveimg(){
				let that = this;
				wx.getSetting({
					success(res) {
						// 如果没有则获取授权
						if (!res.authSetting['scope.writePhotosAlbum']) {
							wx.authorize({
								scope: 'scope.writePhotosAlbum',
								success() {
									wx.saveImageToPhotosAlbum({
										filePath: that.canvasToTempFilePath,
										success() {
											uni.showToast({
												title: '保存成功',
												icon: 'success'
											})
										},
										fail() {
											uni.showToast({
												title: '保存失败',
												icon: 'none'
											})
										}
									})
								},
								fail() {
									// 如果用户拒绝过或没有授权，则再次打开授权窗口
									//（ps：微信api又改了现在只能通过button才能打开授权设置，以前通过openSet就可打开，下面有打开授权的button弹窗代码）
									this.openSet=true
								}
							})
						} else {
							// 有则直接保存
							console.log(that,1111)

							wx.saveImageToPhotosAlbum({
								filePath: that.canvasToTempFilePath,
								success() {
									uni.showToast({
										title: '保存成功',
										icon: 'success'
									})
								},
								fail() {
									uni.showToast({
										title: '保存失败',
										icon: 'none'
									})
								}
							})
						}
					}
				})
			},
			can(){
				let img=this.img,
					img2=this.img2;
				if(!img||!img2){
					return;
				}
				if(this.canvasToTempFilePath){
					this.popup=true
					return
				}
				const ctx = uni.createCanvasContext('canvas_poster');
				ctx.clearRect(0, 0, 0, 0);

				ctx.setFontSize(11);
				var chr =this.details.shareContent.split("");//这个方法是将一个字符串分割成字符串数组
				var temp = "";
				var row = [];
				for (var a = 0; a < chr.length; a++) {
					if ( ctx.measureText(temp).width < this.width*0.8-20) {
						temp += chr[a];
					}
					else {
						a--; //这里添加了a-- 是为了防止字符丢失
						row.push(temp);
						temp = "";
					}
				}
				row.push(temp);
				//如果数组长度大于2 则截取前两个
				if (row.length > 6) {
					var rowCut = row.slice(0, 6 );
					var rowPart = rowCut[1];
					var test = "";
					var empty = [];
					for (var a = 0; a < rowPart.length; a++) {
						if ( ctx.measureText(test).width < 220) {
							test += rowPart[a];
						}
						else {
							break;
						}
					}
					empty.push(test);
					var group = empty[0] + "..."//这里只显示两行，超出的用...表示
					console.log(empty,rowCut)

					rowCut.splice(rowCut.length-1, 1, rowCut[rowCut.length-1]+'...');
					row = rowCut;
				}
				this.height= this.width*0.8*0.4392+170 + row.length * 16

				//背景色
				ctx.setFillStyle('white')
				ctx.fillRect(0,0, this.width*0.8, this.height)

				ctx.setFillStyle('#000000')
				for (var b = 0; b < row.length; b++) {
					ctx.fillText(row[b], 10, this.width*0.8*0.4392+66 + b * 16, this.width*0.8-20);
				}
				ctx.drawImage(img, 0, 0, this.width*0.8, this.width*0.8*0.4392)

				//文字
				ctx.setTextAlign('left')
				ctx.setFontSize(18);
				ctx.setFillStyle('white')
				ctx.fillText(this.details.title, 12, this.width*0.8*0.28,this.width*0.8-20);
				ctx.setFontSize(14);
				ctx.setFillStyle('#000000')
				ctx.fillText(this.details.userName, 50, this.width*0.8*0.4392+22);
				ctx.setFontSize(9);
				ctx.setFillStyle('#7B7B7B')
				ctx.fillText(this.details.createTime, 50, this.width*0.8*0.4392+37);


				// ctx.fillText(this.cc, 10, this.width*0.8*0.4392+66,this.width*0.8-20);


				// ctx.draw()
				//二维码
				ctx.drawImage(img, this.width*0.5,this.width*0.8*0.4392+70 + row.length * 16,
						this.width*0.2, this.width*0.2)
				//矩形
				ctx.setFillStyle('#F5D42D')
				ctx.fillRect(10, this.width*0.8*0.4392+120 + row.length * 16, 14, 3)
				// ctx.draw()
				ctx.setFontSize(10);
				ctx.setFillStyle('#403F3F')
				ctx.fillText(`长按识别小程序，查看更多`, 10, this.width*0.8*0.4392+140 + row.length * 16,
						this.width*0.8-20);


				//头像
				let avatarurl_width = 30, //绘制的头像宽度
						avatarurl_heigth = 30, //绘制的头像高度
						avatarurl_x = 10, //绘制的头像在画布上的位置
						avatarurl_y = this.width*0.8*0.4392+10; //绘制的头像在画布上的位置
				ctx.save(); // 先保存状态 已便于画完圆再用
				ctx.beginPath(); //开始绘制
				//先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
				ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0,
						Math.PI * 2, false);
				ctx.clip(); //画了圆 再剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内
				ctx.drawImage(img2, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth); // 推进去图片
				ctx.drawImage(img2, avatarurl_x, avatarurl_y+20, avatarurl_width, avatarurl_heigth); // 推进去图片
				ctx.draw();
				this.popup=true
				setTimeout(()=>{
					this.save()
				},200)

				// uni.setNavigationBarTitle({
				// 	title: options.data  //修改title
				// })

			},
			sliderChanging(e,item){
				item.timeFlag=true
				item.timeTemp=e.detail.value
				if(item.timeTemp>=item.duration-1){
					item.timeTemp=item.duration-1
				}
				item.currentTimeText=this.getText(item.timeTemp)
			},
			sliderChange(e,item){
				item.timeFlag=false
				item.currentTime=item.timeTemp
				if(item.flag){
					this.backgroundAudioManager.seek(item.currentTime)
				}
			},
			getText(time){
				return (Math.floor(time/60)<10?'0'+Math.floor(time/60):Math.floor(time/60))+':'+
						(Math.floor(time%60)<10?'0'+Math.floor(time%60):Math.floor(time%60))
			},
			audioPlay(item,index) {
				if(item.flag){
					this.backgroundAudioManager.pause()
					this.timer?clearInterval(this.timer):''
				}else{
					console.log(this.backgroundAudioManager.url,item.url,88888888)
					if(this.index!=index||!this.backgroundAudioManager.src){
						this.timer?clearInterval(this.timer):''
						if(this.index>-1){
							this.details.attachments[this.index].currentTime=0
							this.details.attachments[this.index].currentTimeText='00:00'
							this.details.attachments[this.index].flag=false
						}
						this.backgroundAudioManager.pause()
						this.backgroundAudioManager.epname = item.name
						this.backgroundAudioManager.title = item.name
						this.backgroundAudioManager.singer = this.details.userName
						this.backgroundAudioManager.src = item.url
					}
					this.backgroundAudioManager.seek(item.currentTime)
					this.backgroundAudioManager.play()
					this.timer=setInterval(()=>{
						if(this.timeFlag){
							return
						}
						item.currentTime++
						item.currentTimeText=this.getText(item.currentTime)
					},1000)
				}
				this.index=index
				item.flag=!item.flag
			},
			audio(item,index){
				this.backgroundAudioManager = uni.getBackgroundAudioManager()
				this.backgroundAudioManager.onCanplay(res=>{
					// this.backgroundAudioManager.pause()
					console.log(this.backgroundAudioManager,55555)
				})
				this.backgroundAudioManager.onEnded(res=>{
					this.timer?clearInterval(this.timer):''
					this.details.attachments[this.index].currentTime=0
					this.details.attachments[this.index].currentTimeText='00:00'
					this.details.attachments[this.index].flag=false
					this.backgroundAudioManager.src =''

				})
			},
		}
	}
</script>

<style scoped>
	button:after {
		border-width: 0;
	}
	audio{
		width: 100% !important;
	}
	.top{
		box-shadow: 0px 2px 2px 0px rgba(240, 240, 240, 1);
		padding: 20upx 30upx;
		width: calc(100% - 60upx);
		background: white;
		position: fixed;
		color: rgba(16, 16, 16, 1);
		font-size: 42upx;
		font-family: PingFangSC-bold;
	}
	.line{
		height: 120upx;
		width:100%;
		background:#FAFAFA;
	}
	.content{
		padding:0 30upx;
	}
	.content-image{
		width: 60upx;
		height: 60upx;
		border-radius: 60upx;
		margin-right:10upx;
	}
	.content-name{
		color: rgba(0, 0, 0, 1);
		font-size: 28upx;
		font-family: PingFangSC-regular;
	}
	.content-time{
		color: rgba(123, 123, 123, 1);
		font-size: 18upx;
		font-family: PingFangSC-regular;
	}
	.content-text{
		margin: 20upx 0;
		color: rgba(16, 16, 16, 1);
		font-size: 28upx;
		font-family: PingFangSC-regular;
	}
	.audio-wrap{
		width: 100%;
		margin-bottom: 20upx;
		line-height: 40upx;
		border-radius: 16upx;
		background-color: rgba(247, 247, 247, 1);
		display: flex;
	}
	.audio-title{
		color: rgba(16, 16, 16, 1);
		font-size: 32upx;
		font-family: PingFangSC-regular;
	}
	.audio-time{
		color: rgba(181, 181, 181, 1);
		font-size: 26upx;
		font-family: PingFangSC-regular;
		display: flex;
		justify-content: space-between;
	}
	.footer{
		display: flex;
		justify-content: space-between;
		width: calc(100% - 120upx);
		position: fixed;
		bottom:  0px;
		box-shadow: 0px 0px 8px 4px rgba(240, 240, 240, 1);
		background: white;
		color: rgba(183, 183, 183, 1);
		font-size: 26upx;
		font-family: PingFangSC-regular;
		padding: 30upx 60upx;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		/*margin-bottom: ;*/
	}
	.share{
		margin-bottom: 30upx;
		text-align: center
	}
	.popup{
		border-radius: 12upx;
		overflow: hidden;
		color: rgba(16, 16, 16, 1);
		box-shadow: 0px 0px 4px 3px rgba(242, 242, 242, 1);
		font-family: -apple-system;
		width: 80%;
		height: 300px;
		margin-left: 10%;
	}
	.save{
		width: 282upx;
		height: 80upx;
		line-height: 80upx;
		margin: 40upx calc(50% - 141upx);
		border-radius: 180upx;
		color: white;
		background-color: rgba(26, 130, 255, 1);
		text-align: center;
	}
</style>
